#!/usr/bin/python
#-*- coding:utf-8 -*-
import os, sys, shutil, platform, email.message, smtplib, time, shutil, optparse, httplib, zipfile
def already_open():
	if "lock" in os.listdir(os.path.join(os.path.expanduser("~"), ".wxsoft")):
		return 1
	else:
		f = open(os.path.join(os.path.expanduser("~"), ".wxsoft", "lock"), "w")
		f.close()
		os.chmod(os.path.join(os.path.expanduser("~"), ".wxsoft", "lock"), 000)
		return 0
def autocheck(version):
	try:
		prefix = parse_path(sys.argv, autocheck=True)
		http = httplib.HTTPConnection("pythonprojects.altervista.org")
		http.request("GET", "/VERSION")
		resp = http.getresponse()
		response = resp.read()
		if response.split(":")[1] != version and response.split(":")[1] > version:
			version = response.split(":")[1]
			http = httplib.HTTPConnection("pythonprojects.altervista.org")
			http.request("GET", "/wxsoft-archive/wxsoft-"+version+".zip")
			resp = http.getresponse()
			response = resp.read()
			file = open(os.path.join(os.path.expanduser("~"), ".wxsoft", "archive", "wxsoft-"+version+".zip"), "r+")
			file.write(response)
			file.seek(0)
			fz = zipfile.ZipFile(file)
			file.close()
			fz.extractall(os.path.dirname(prefix))
			shutil.move(os.path.join(os.path.expanduser("~"), ".wxsoft", "archive", "wxsoft-"+version+".zip"), os.path.join(os.path.expanduser("~"), ".wxsoft", "archive", "old"))
			main = fz.namelist()
			fz.close()
			return "wxsoft/main.py" in main
	except:
		pass
def check_module():
	app = []
	if platform.python_version() < "2.6":
		raise PythonVersionError("The version of Python is too old. You need Python 2.6 >=")
	try:
		import wxversion
	except ImportError:
		raise ModuleError("You haven't wxPython installed")
	else:
		wx1 = wxversion.getInstalled()
		if wx1 == []:
			raise ModuleError("You haven't wxPython installed")
		sel = False
		for version in wx1:
			if version >= "2.8" and not sel:
				wxversion.select(version)
				sel = True
		if not sel:
			raise ModuleError("The version of wxPython is too old. You need wxPython 2.8 >=")
		else:
			app.append("wxEdit")
		try:
			import libtorrent
		except ImportError:
			pass
		else:
			app.append("wxTorrent")
		return app
def firstopen(args):
	args = args[0]
	if ".wxsoft" not in os.listdir(os.path.expanduser("~")):
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft"))
		if platform.system() == "Windows":
			os.system("ATTRIB +H "+os.path.join(os.path.expanduser("~"), ".wxsoft")+" /S")
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft", "archive"))
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft", "archive", "old"))
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft", "email"))
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft", "wxedit"))
		os.mkdir(os.path.join(os.path.expanduser("~"), ".wxsoft", "wxtorrent"))
		if ("./" in args and "../" not in args) or os.path.dirname(args) == "":
			path = os.path.join(os.getcwd(), "wxedit", "config", "wxedit.ini")
		else:
			path = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), "wxedit", "config", "wxedit.ini")
		shutil.copy(path, os.path.join(os.path.expanduser("~"), ".wxsoft", "wxedit"))
def parse(version, **kwargs):
	version = """ Name: wxSoft
 Version = """+version+"""
 Author: Alessio'Alexei95' Colucci <alessio.colucci@live.it>
 Copyright: Copyright (C) 2009 Alessio 'Alexei95' Colucci
 License:

	wxSoft is a combination of Editor, client BitTorrent, ... written in Python (GUI - wxPython)

	Copyright (C) 2009  Alessio "Alexei95" Colucci

	wxSoft is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	any later version.

	wxSoft is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with wxSoft.  If not, see <http://www.gnu.org/licenses/>.

 For bug visit pythonprojects.altervista.org or write an e-mail to bugpythonprojects@gmail.com"""
	editor = kwargs["editor"]
	torrent = kwargs["torrent"]
	parser = optparse.OptionParser(version=version, usage="%prog FILE1, FILE2... [options]")
	parser.add_option("-t", "--torrent", action="store_true", dest="torrent", default=False, help="open the files FILE1, FILE2... with wxTorrent")
	parser.add_option("-e", "--editor", action="store_true", dest="editor", default=False, help="open the files FILE1, FILE2... with wxEdit")
	parser.add_option("-r", "--read-only", action="store_true", dest="read_only", default=False, help="set the files as read-only with wxEdit")
	parser.add_option("-b", "--bug-reporter", action="store_true", dest="bug_report", default=False, help="use the bug reporter")
	parser.add_option("-n", "--no-check", action="store_true", dest="check", default=True, help="no check the site for new version")
	args = []
	(options, args) = parser.parse(sys.argv)
	if not options.torrent and not options.editor and not options.bug_report:
		parser.error("you MUST selected one of: -t, -e, -b")
	elif options.torrent:
		pass
	elif options.editor:
		pass
	elif options.bug_report:
		pass
def parse_path(args, autocheck=False):
	args = args[0]
	if autocheck:
		if ("./" in args and "../" not in args) or os.path.dirname(args) == "":
			prefix1 = os.path.join(os.getcwd())
		else:
			prefix1 = os.path.join(os.getcwd(), os.path.dirname(args))
		return prefix1
	else:
		if ("./" in args and "../" not in args) or os.path.dirname(args) == "":
			prefix1 = os.path.join(os.getcwd(), "icons", "16x16", "actions", "")
			prefix2 = os.path.join(os.getcwd(), "icons", "24x24", "actions", "")
			prefix3 = os.path.join(os.getcwd(), "icons", "")
		else:
			prefix1 = os.path.join(os.getcwd(), os.path.dirname(args), "icons", "16x16", "actions", "")
			prefix2 = os.path.join(os.getcwd(), os.path.dirname(args), "icons", "24x24", "actions", "")
			prefix3 = os.path.join(os.getcwd(), os.path.dirname(args), "icons", "")
		return (prefix1, prefix2, prefix3)
def sendmail(host, text, sub, port, app, program, version, to="bugpythonprojects@gmail.com", path=os.path.join(os.path.expanduser("~"), ".wxsoft", "email"), file=None):
	if app in ("y", "yes", "Y", "YES", "Yes", "True", "true", "1", ""):
		app = True
	else:
		app = False
	if host == "":
		host = "out.aliceposta.it"
	if text == "":
		text = "Founded new bug on %s. More info on the attached file if apport is present on the machine." % os.path.basename(sys.argv[0])
	if sub == "":
		sub = "New bug"
	if port == "":
		port = 25
	else:
		try:
			port = int(port)
		except ValueError:
			port = 25
	try:
		import apport
		appor = True
	except ImportError:
		appor = False
	msg = "From: %s\n\nTo: %s\n\nSubject: %s\n\n" % (to, to, sub)
	from wx import __version__ as wxVERSION
	info = """PythonCompiler: %s
PythonBuild: %s
PythonVersion: %s
wxPythonVersion: %s
Program: %s
Version: %s""" % (platform.python_compiler(), platform.python_build(), platform.python_version(), wxVERSION, program, version)
	if appor and app:
		file = "".join([time.asctime(), ".rpt"])
		f = open(os.path.join(path, file), "w")
		app = apport.report.Report()
		app.add_user_info()
		app.anonymize()
		app.add_os_info()
		app.add_proc_info()
		app.add_proc_environ()
		app.add_package_info()
		app.write(f)
		f.close()
		f = open(os.path.join(path, file), "r")
		a = f.read()
		f.close()
		os.remove(os.path.join(path, file))
		msg += "%s\n\n\n\n\tInfo (platform/os/sys):\n\n%s\n\n\tInfo (apport):\n\n%s" % (text, info, a)
	else:
		msg += "%s\n\n\n\n\tInfo (platform/os/sys):\n\n%s" % (text, info)
	file2 = "".join([time.asctime(), ".mail"])
	f = open(os.path.join(path, file2), "w")
	f.write(msg)
	f.close()
	smtp = smtplib.SMTP(host, port)
	try:
		smtp.sendmail(to, to, msg)
	except:
		host = "out.aliceposta.it"
		smtp.sendmail(to, to, msg)
	smtp.quit()
	return 1

		